package wiki

import (
	"jiabo/appframework/libs/db"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
)

type Wiki struct {
	Id      bson.ObjectId `bson:"_id,omitempty" json:"-"`
	Title   string        `bson:"title" json:"title"`
	Content string        `bson:"content" json:"content"`
	Log     string        `bson:"log" json:"log"`
}

///===========================================================

func SearchWiki(q interface{}) (searchResults []Wiki, searchErr string) {
	searchErr = ""
	searchResults = []Wiki{}
	query := func(c *mgo.Collection) error {
		fn := c.Find(q).All(&searchResults)
		return fn
	}
	search := func() error {
		return db.WithCollection("wikis", query)
	}
	err := search()
	if err != nil {
		searchErr = "Database Error"
	}

	return
}

func GetWikiByTitle(title string) (searchResults []Wiki, searchErr string) {
	searchResults, searchErr = SearchWiki(bson.M{"title": title})
	return
}

func InsertWiki(wiki Wiki) error {
	insert := func(c *mgo.Collection) error {
		fn := c.Insert(wiki)
		return fn
	}

	insertExec := func() error {
		return db.WithCollection("wikis", insert)
	}

	err := insertExec()

	return err
}

func UpdateWiki(wiki Wiki) error {
	update := func(c *mgo.Collection) error {
		fn := c.Update(bson.M{"title": wiki.Title}, wiki)
		return fn
	}

	updateExec := func() error {
		return db.WithCollection("wikis", update)
	}

	err := updateExec()

	return err
}
